package net.spider.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class SankakuDao {

	private static final String INSERT_SQL = "insert into sankaku values (?, ?);";
	private static final String QUERY_SQL = "select * from sankaku where id = ?;";
	private static final String TEST_SQL = "select * from sankaku where 1 = 2;";
	private static final String INIT_SQL = "create table sankaku (id primary key, url);";

	public static void init() {
		try {
			Connection conn = DB.getConnection();
			Statement stat = conn.createStatement();
			try {
				stat.execute(TEST_SQL);
			} catch (SQLException e) {
				stat.executeUpdate(INIT_SQL);
			}
			stat.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public static synchronized void insert(String id, String url) {
		PreparedStatement prep = null;
		try {
			prep = DB.getConnection().prepareStatement(INSERT_SQL);
			prep.setString(1, id);
			prep.setString(2, url);
			prep.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			if (prep != null)
				try {
					prep.close();
				} catch (SQLException e) {
				}
		}
	}

	public static boolean isExists(String id) {
		PreparedStatement prep = null;
		ResultSet rs = null;
		try {
			prep = DB.getConnection().prepareStatement(QUERY_SQL);
			prep.setString(1, id);
			rs = prep.executeQuery();
			if (rs.next())
				return true;
			else
				return false;
		} catch (SQLException e) {
			e.printStackTrace();
			return true;
		} finally {
			if (rs != null)
				try {
					rs.close();
				} catch (SQLException e) {
				}
			if (prep != null)
				try {
					prep.close();
				} catch (SQLException e) {
				}
		}
	}

}
